<template>
  <view class="container">
    <view class="calendar-wrapper">
      <Calendar :active-days="hasScoreDays.days" @date-change="dateChange" />
    </view>
    <view class="task-title">
      任务趋势
    </view>
    <view class="chart-wrapper">
      <l-echart ref="chartRef" class="chart" />
    </view>
    <view class="task-title">
      任务记录
    </view>
    <template v-if="lists.length">
      <view v-for="item in lists" :key="item.recordDate" class="task-item" @click="goDetails(item)">
        <view class="col-l">
          {{ item.recordDate }}
        </view>
        <view class="col-r">
          <text v-if="item.completedPoints">+{{ item.completedPoints }}</text>
          <IconMore class="more" :is-right="true" />
        </view>
      </view>
    </template>
    <wd-status-tip v-else image="message" tip="没有任何内容哦" />
    <view class="empty-container" />
  </view>
</template>

<script lang="ts" setup>
import type { IDailyTask } from '@/api/task'
import { deepClone } from '@alova/shared'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { storeToRefs } from 'pinia'
import { queryTaskRecord } from '@/api/task'
import Calendar from '@/components/Calendar.vue'
import IconMore from '@/components/IconMore.vue'
import { useChildStore } from '@/store/child'

const today = dayjs()
const selectedDay = ref(today)
const chartRef = ref()
const chartInstance = ref()
const lists = ref<IDailyTask[]>([])

definePage({
  // 使用 type: "home" 属性设置首页，其他页面不需要设置，默认为page
  // type: 'home',
  style: {
    // 'custom' 表示开启自定义导航栏，默认 'default'
    navigationStyle: 'default',
    navigationBarTitleText: '任务记录',
    backgroundColor: '#fafafa',
  },
})

const option = {
  grid: {
    left: 10,
    right: 10,
    top: 20,
    bottom: 10,
  },
  xAxis: {
    axisTick: { show: false },
    axisLabel: { show: false },
    axisLine: { show: false },
    splitLine: { show: false },
    type: 'category',
    data: [],
  },
  yAxis: {
    type: 'value',
    axisTick: { show: false },
    axisLabel: { show: false },
    axisLine: { show: false },
    splitLine: { show: false },
  },
  series: [
    {
      data: [],
      type: 'line',
      smooth: true,
      itemStyle: {
        color: '#435d00',
      },
      label: {
        show: true,
        position: 'top',
        color: '#435d00',
      },
      areaStyle: {
        opacity: 0.8,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(132, 178, 15,1)',
          },
          {
            offset: 1,
            color: 'rgba(132, 178, 15,0)',
          },
        ]),
      },
    },
  ],
}

// #region Props
// #endregion
// #region Emits
// #endregion
// #region Hooks
const childStore = useChildStore()
const { selectedChild } = storeToRefs(childStore)
// #endregion
// #region Computed
const dateRange = computed(() => {
  const startDay = selectedDay.value.startOf('month').format('YYYY-MM-DD')
  const end = selectedDay.value.endOf('month')
  const endDay = end.isBefore(today) ? end.format('YYYY-MM-DD') : today.format('YYYY-MM-DD')
  return { startDay, endDay }
})

const hasScoreDays = computed(() => {
  const days = []
  const points = []
  for (let index = 0; index < lists.value.length; index++) {
    const item = lists.value[index]
    if (item.completedCount > 0) {
      days.push(Number(dayjs(item.recordDate).date()))
      points.push(item.completedPoints)
    }
  }
  return { days, points }
})

const mouthDay = computed(() => {
  return dayjs(dateRange.value.endDay).date()
})
// #endregion
// #region Watch
// #endregion
// #region Event
// #endregion
// #region Function
function updateChart() {
  const data = []
  const xAxisData = []
  const options = deepClone(option)
  for (let index = 0; index < mouthDay.value; index++) {
    xAxisData.push(`${index + 1}`)
    const findIndex = hasScoreDays.value.days.findIndex(item => item === index + 1)
    if (findIndex > -1) {
      data.push(hasScoreDays.value.points[findIndex])
    }
    else {
      data.push(0)
    }
  }
  options.xAxis.data = xAxisData
  options.series[0].data = data
  if (chartInstance.value) {
    chartInstance.value.clear()
    chartInstance.value.setOption(options, true)
  }
}

async function initChart() {
  if (!chartRef.value)
    return

  try {
    chartInstance.value = await chartRef.value.init(echarts)
    query()
  }
  catch (error) {
    console.error('图表初始化失败:', error)
  }
}

function query() {
  queryTaskRecord({
    childId: selectedChild.value.id,
    startDate: dateRange.value.startDay,
    endDate: dateRange.value.endDay,
  }).then((res) => {
    lists.value = res
    updateChart()
  })
}

function dateChange(date: dayjs.Dayjs) {
  selectedDay.value = date
  initChart()
}

function goDetails(item: IDailyTask) {
  uni.navigateTo({ url: `/pages/history-details/index?params=${encodeURIComponent(JSON.stringify(item))}` })
}
// #endregion
// #region Life Cycle
onReady(() => {
  initChart()
})
// #endregion
// #region Expose
// #endregion
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  background: var(--bg-color);
  overflow-y: scroll;
  .calendar-wrapper {
    background: var(--card-border-color);
    border-radius: 16px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border: 1px solid var(--card-border-gary-color);
    margin: 10px 10px 0 10px;
    padding: 10px;
  }
  .chart-wrapper {
    height: 200px;
    background: var(--card-border-color);
    padding: 20px 0;
    border-top: 1px solid var(--card-border-gary-color);
    border-bottom: 1px solid var(--card-border-gary-color);
  }
  .chart {
    width: 100%;
    height: 100%;
  }
  .task-title {
    font-weight: 600px;
    color: var(--main-color);
    font-size: 20px;
    margin: 20px 10px;
  }

  .task-item {
    background: var(--card-border-color);
    padding: 20px 10px;
    font-size: 16px;
    border-bottom: 1px solid var(--checkbox-border-color);
    display: flex;
    align-items: center;
    justify-content: space-between;
    .col-l {
      flex: 1 0 auto;
      width: 50%;
    }
    .col-r {
      display: flex;
      align-items: center;
      gap: 10px;
      text {
        color: var(--light-color);
        font-size: 20px;
        font-weight: bold;
      }
      .more {
      }
    }
  }
  .empty-container {
    height: env(safe-area-inset-bottom);
  }
}
</style>
